package com.woniuxy.dudugua.controller;

import com.woniuxy.dudugua.entity.Cart;
import com.woniuxy.dudugua.entity.User;
import com.woniuxy.dudugua.service.CartService;
import com.woniuxy.dudugua.util.Result;
import com.woniuxy.dudugua.util.view.CartView;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("cart")
public class CartController {
    @Autowired
    private CartService cartService;
    @RequestMapping("getcart")
    public Result getCart(){
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        List<CartView> cartView = cartService.getCartView(user.getId());
        return new Result("200","success",null,cartView);
    }
    @RequestMapping("delete")
    public Result delete(int id){
        int i = cartService.deleteCart(id);
        return new Result("200","success",null,null);
    }
    @RequestMapping("empty")
    public Result delete(){
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        int i = cartService.deleteUserCart(user.getId());
        return new Result("200","success",null,null);
    }
    @RequestMapping("update")
    public Result updateNumber(int id,int number){
            int i = cartService.updateNumber(id, number);
            return new Result("200", "success", null, null);
    }
    @RequestMapping("insert")
    public Result insertCart(int id,int number){
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        Cart cart1 = cartService.selectCart(id, user.getId());
        if(cart1==null) {
            Cart cart = new Cart();
            cart.setProductId(id);
            cart.setNumber(number);
            cart.setUserId(user.getId());
            cartService.insertCart(cart);
        }else{
            cart1.setNumber(cart1.getNumber()+number);
            cartService.updateCart(cart1);
        }
        return new Result("200", "success", null, null);
    }
}
